<template>
  <div class="cards">
    <van-swipe class="cards-swipe" :autoplay="3000">
      <van-swipe-item v-for="thumb in hotelImages" :key="thumb">
        <img :src="thumb" />
      </van-swipe-item>
    </van-swipe>

    <h3 style="padding: 16px;">{{ hotelName }}</h3>

    <div v-if="isLogin === 'Login'">
      <HMemberCardVue v-for="(card, index) in memberCards" :key="index" @click="onMemberCardClicked(card)" :card="card" show-status show-balance />
    </div>

    <van-popup v-model:show="show" :close-on-click-overlay="false" :style="{ padding: '20px' }">
      <img :src="qrcodeUrl" width="300" height="300" />
    
      <p style="text-align: center; color: red;">使用时请将此二维码出示给酒店服务员</p>
    </van-popup>

    <p v-show="show" class="close-qrcode" @click="closeQRCode">>>收起二维码<<</p>

    <div v-if="isLogin === 'NoMobile'">
      <p style="text-align: center;">请验证会员卡登记的手机号</p>
      
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="formData.mobile"
            name="mobile"
            label="手机号"
            placeholder="请输入手机号"
            clearable
            :maxlength="11"
            :rules="[{ required: true, message: '请输入手机号' }, { validator: validatorMobile, message: '无效的手机号' }]"
          />
         
          <van-field
            v-model="formData.captcha"
            name="captcha"
            center
            clearable
            label="短信验证码"
            placeholder="请输入短信验证码"
            :maxlength="6"
            :rules="[{ required: true, message: '请输入验证码' }]"
          >
            <template #button>
              <van-button size="small" type="primary" @click="getCaptcha" :disabled="disableCaptcha">发送验证码<span v-if="waiting > 0">({{ waiting }}秒)</span></van-button>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :disabled="disableSubmit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>

    <div v-if="isLogin === 'NoInit'">
      <div style="text-align: center;"><van-loading type="spinner" /></div>
    </div>

  </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { reactive, computed, ref, watch, onMounted, onUnmounted } from 'vue';
// import { useRoute } from 'vue-router'
import QRCode, { QRCodeToDataURLOptions } from 'qrcode'
import { useAppStore } from '@/store/modules/app'
import { getCaptchaApi, captchaLoginApi, getHMemberCardListApi, openid2tokenApi } from '@/api/wechat'
import { getOpenId } from '@/utils';
import type { HMemberCard } from '@/api/wechat/types'
import { useCache, tokenKey } from '@/hooks/web/useCache'
import HMemberCardVue from '@/components/HMemberCard.vue'

const appStore = useAppStore()
appStore.setTabbarIndex(0)

const show = ref<boolean>(false)
const qrcodeUrl = ref<string>('')
const waiting = ref<number>(0)
const hotelName = computed(() => appStore.getHotelName)
const hotelImages = computed(() => appStore.getImages)

const { wsCache } = useCache()
const waitingKey = 'sms-captcha-waiting'

const memberCards = reactive<HMemberCard[]>([])

const formData = reactive({
  mobile: '',
  captcha: ''
})

const mobile = computed(() => appStore.getMobile)
const isLogin = computed((): 'Login' | 'NoMobile' | 'NoInit' => {
  if (mobile.value === 'undefined') {
    return 'NoInit'
  }

  if (mobile.value.length > 10) {
    return 'Login'
  }
  
  return 'NoMobile'
})

const disableCaptcha = computed((): boolean => {
  return !formData.mobile || formData.mobile.length < 11 || !validatorMobile(formData.mobile) || waiting.value > 0
})

const disableSubmit = computed((): boolean => {
  return !formData.mobile || formData.mobile.length < 11 || !formData.captcha || formData.captcha.length < 6
})

watch(isLogin, () => {
  getMemberCardList()
})

onMounted(() => {
  if (isLogin.value === 'Login') {
    getMemberCardList()
  }
})

const onMemberCardClicked = (card: HMemberCard) => {
  show.value = true

  const opts: QRCodeToDataURLOptions = {
    errorCorrectionLevel: 'H',
    type: 'image/jpeg',
    margin: 1
  }

  QRCode.toDataURL(btoa(`NMM:${card.member_number}/${mobile.value}`), opts, function (err, url) {
    if (err) throw err

    qrcodeUrl.value = url
  })
}

const closeQRCode = () => {
  show.value = false
}

const validatorMobile = (val) => /^1[3-9]\d{9}$/.test(val);

const login = async () => {
  const openid = getOpenId()
  if (openid) {
    // 获取token
    const res = await openid2tokenApi({})
    console.log(res)
    if (res) {
      wsCache.set(tokenKey, res.data.token)
      appStore.setOpenId(res.data.openid)
      appStore.setMobile(res.data.mobile || '')
      appStore.setGuestTitle(res.data.guest_title)
      appStore.setLastName(res.data.last_name)
    }
  } else { // 跳转code页面
    location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appStore.getAppId}&redirect_uri=https%3A%2F%2Flkhg.nmm.wuyi-dev.com%2Fcards&response_type=code&scope=snsapi_base#wechat_redirect`
  }
}

const onSubmit = async (values) => {
  const res = await captchaLoginApi(values)
  console.log(res)
  // appStore.setMobile(res.data.mobile)
  await login()
}

const getMemberCardList = async () => {
  const res = await getHMemberCardListApi()
  memberCards.length = 0
  Object.assign(memberCards, res.data)
}

const getCaptcha = async () => {

  if (dayjs().valueOf() < wsCache.get(waitingKey)) {
    return
  }

  if (formData.mobile) {
    await getCaptchaApi({ phoneNumbers: formData.mobile })
    wsCache.set(waitingKey, dayjs().add(60, 'seconds').valueOf())
  }
}

let timer;
onMounted(() => {
  timer = setInterval(() => {
    const nextTime = wsCache.get(waitingKey)
    if (nextTime) {
      let diff = dayjs(nextTime).diff(dayjs(), 'seconds')
      if (diff < 0) {
        diff = 0
      }

      waiting.value = diff
    } 
  }, 500)
})

onUnmounted(() => {
  clearInterval(timer)
})

</script>

<style lang="scss" scoped>
.close-qrcode {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 10%;
  z-index: 3000;
  color: white;
  text-align: center;
}

.cards {
  padding-bottom: 50px;

  &-swipe {
    img {
      width: 100%;
      display: block;
    }
  }

  &-title {
    font-size: 16px;
  }

  &-price {
    color: #f44;
  }

  &-express {
    color: #999;
    font-size: 12px;
    padding: 5px 15px;
  }

  &-cell-group {
    margin: 15px 0;

    .van-cell__value {
      color: #999;
    }
  }

  &-tag {
    margin-left: 5px;
  }
}

.qrcode {
  width: 300px;
  height: 300px;
} 
</style>
